#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, const char ** argv) {
	int fd;
	struct stat sb;
	void * region;
	const int DATA_LEN = 6;
	char* pData = (char*) malloc(DATA_LEN); 

	//memcpy()
	memcpy(pData,"hebing",DATA_LEN);
	printf("New String is : %s\n\n",pData);

	if ((fd = open(argv[1], O_CREAT|O_RDWR, 00777)) < 0) {
		perror("open");
		return 1;
	}
	/* stat the file so we know how much of it to map into memory */
	if (fstat(fd, &sb)) {
		perror("fstat");
		return 1;
	}

	// mmap()
	region = mmap(NULL, sb.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
	if (region == ((caddr_t) -1)) {
		perror("mmap");
		return 1;
	}
	close(fd);

	//standard output
	printf("File Content are : \n");
	if (write(1, region, sb.st_size) != sb.st_size) {
		perror("write");
		return 1;
	}
	printf("\n");

	memcpy(region, pData, DATA_LEN);
	if (-1 == msync(region, sb.st_size, MS_SYNC))
	{
		perror("msync");
	}
	free(pData);
	pData = NULL;

	printf("New File Content are : \n");
	if (write(1, region, sb.st_size) != sb.st_size) {
		perror("write");
		return 1;
	}
	printf("\n");

	pData = (char*)region;
	printf("Print char[2] : \n");
	printf("%c\n", pData[2]);

	//sleep(1000); // /proc/pid/maps
	if (-1 == munmap(region, sb.st_size))
	{
		perror("munmap");
	}
	//sleep(1000); // /proc/pid/maps
	
	return 0;
}
